import { createRouter, createWebHashHistory } from 'vue-router'
import { getLocal } from '@/utils/cookie'
// import Layout from '@/views/index'
const router = createRouter({
  history: createWebHashHistory(), // hash模式：createWebHashHistory,history模式：createWebHistory
  routes: [
    {
      path: '/',
      component: () => import('@/views/index'),
      redirect: '/home',
      children: [
        {
          path: 'home',
          name: 'home',
          component: () => import('@/views/home/index'),
          meta: {
            title: '鼎音之家 - 智慧营业厅',
            content:{
              keywords:'',
              description:''
            }
          },
        },
      ],
    },

    {
      path: '/:mathAll(.*)',
      name: 'notfound',
      component: () => import('@/views/404/404'),
    },
    {
      path:'/login',
      name:'login',
      component: () => import('@/views/login/login'),
      meta: {
        title: '登录',
      },
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/login/register'),
      meta: {
        title: '注册',
      },
    },
  ],
})

router.beforeEach((to, from, next) => {
  if (to.meta.content) {
    let head = document.getElementsByTagName('head');
    let meta = document.createElement('meta');
    document.querySelector('meta[name="keywords"]').setAttribute('content', to.meta.content.keywords)
    document.querySelector('meta[name="description"]').setAttribute('content', to.meta.content.description)
    meta.content = to.meta.content;
    head[0].appendChild(meta)
  }
  if (to.meta.title) {
    document.title = to.meta.title
  } 
  next()
  if(to.path=='/login'){
    return next()
  }
  const token = getLocal('raySaleToken')
  if(!to.meta.requireAuth){
    //没有设置requireAuth直接访问即可
    next()
  }else{
    //存在就登录
    if(token){//已登录就放行
      next()
    }else{//未登录跳登录页
      next(`/login?redirect=${to.fullPath}`)
    }
  }

})

export default router
